## Sid Meier's Civilization 4
## Copyright Firaxis Games 2005

from CvPythonExtensions import *
import CvUtil
import Popup as PyPopup
import PyHelpers
import CvScreenEnums

# globals
gc = CyGlobalContext()
PyPlayer = PyHelpers.PyPlayer

class CustomFunctions:

	def addBonus(self, iBonus, iNum, sIcon):
		listPlots = []
		for i in range (CyMap().numPlots()):
			pPlot = CyMap().plotByIndex(i)
			if (pPlot.canHaveBonus(gc.getInfoTypeForString(iBonus),True) and pPlot.getBonusType(-1) == -1 and pPlot.isCity() == False):
				listPlots.append(i)
		if len(listPlots) > 0:
			for i in range (iNum):
				iRnd = CyGame().getSorenRandNum(len(listPlots), "Add Bonus")
				pPlot = CyMap().plotByIndex(listPlots[iRnd])
				pPlot.setBonusType(gc.getInfoTypeForString(iBonus))
				if sIcon != -1:
					iActivePlayer = CyGame().getActivePlayer()
					CyInterface().addMessage(iActivePlayer,True,25,CyTranslator().getText("TXT_KEY_MESSAGE_RESOURCE_DISCOVERED",()),'AS2D_DISCOVERBONUS',1,sIcon,ColorTypes(8),pPlot.getX(),pPlot.getY(),True,True)

	def addPopup(self, szText, sDDS):
		szTitle = self.szGameDate = CyGameTextMgr().getTimeStr(CyGame().getGameTurn(), false)
		popup = PyPopup.PyPopup(-1)
		popup.addDDS(sDDS, 0, 0, 128, 384)
		popup.addSeparator()
		popup.setHeaderString(szTitle)
		popup.setBodyString(szText)
		popup.launch(true, PopupStates.POPUPSTATE_IMMEDIATE)

	def addPopupWB(self, szText, sDDS):
		szTitle = self.szGameDate = CyGameTextMgr().getTimeStr(CyGame().getGameTurn(), false)
		screen = CyGInterfaceScreen( "MainInterface", CvScreenEnums.MAIN_INTERFACE )
		xRes = screen.getXResolution()
		yRes = screen.getYResolution()
		popup = PyPopup.PyPopup(-1)
		popup.addDDS(sDDS, 0, 0, 500, 800)
		popup.addSeparator()
		popup.setHeaderString(szTitle)
		popup.setBodyString(szText)
		popup.setPosition((xRes - 840) / 2,(yRes - 640) / 2)
		popup.setSize(840, 640)
		popup.launch(true, PopupStates.POPUPSTATE_IMMEDIATE)

	def addPlayerPopup(self, szText, iPlayer):
		popupInfo = CyPopupInfo()
		popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
		popupInfo.setText(szText)
		popupInfo.addPythonButton(CyTranslator().getText("TXT_KEY_POPUP_CLOSE", ()), "")
		popupInfo.addPopup(iPlayer)

	def addUnit(self, iUnit):
		pBestPlot = -1
		iBestPlot = -1
		for i in range (CyMap().numPlots()):
			pPlot = CyMap().plotByIndex(i)
			iPlot = -1
			if pPlot.isWater() == False:
				if pPlot.getNumUnits() == 0:
					if pPlot.isCity() == False:
						if pPlot.isImpassable() == False:
							iPlot = CyGame().getSorenRandNum(500, "Add Unit")
							iPlot = iPlot + (pPlot.area().getNumTiles() * 10)
							if pPlot.isBarbarian():
								iPlot = iPlot + 200
							if pPlot.isOwned():
								iPlot = iPlot / 2
							if iPlot > iBestPlot:
								iBestPlot = iPlot
								pBestPlot = pPlot
		if iBestPlot != -1:
			bPlayer = gc.getPlayer(gc.getBARBARIAN_PLAYER())
			newUnit = bPlayer.initUnit(iUnit, pBestPlot.getX(), pBestPlot.getY(), UnitAITypes.NO_UNITAI, DirectionTypes.DIRECTION_SOUTH)

	def doCrusade(self, iPlayer):
		iCrusadeChance = gc.getDefineINT('CRUSADE_SPAWN_CHANCE')
		iDemagog = gc.getInfoTypeForString('UNIT_DEMAGOG')
		iTown = gc.getInfoTypeForString('IMPROVEMENT_TOWN')
		iVillage = gc.getInfoTypeForString('IMPROVEMENT_VILLAGE')
		for i in range (CyMap().numPlots()):
			pPlot = CyMap().plotByIndex(i)
			if pPlot.isOwned():
				if pPlot.getOwner() == iPlayer:
					if pPlot.getImprovementType() == iTown:
						if CyGame().getSorenRandNum(100, "Crusade") <= iCrusadeChance:
							pPlayer = gc.getPlayer(iPlayer)
							newUnit = pPlayer.initUnit(iDemagog, pPlot.getX(), pPlot.getY(), UnitAITypes.NO_UNITAI, DirectionTypes.DIRECTION_SOUTH)
							pPlot.setImprovementType(iVillage)

	def formEmpire(self, iCiv, iLeader, iTeam, pCity, iAlignment):
		iPlayer = self.getOpenPlayer()
		pPlot = pCity.plot()
		pPlot2 = self.findClearPlot(-1, pCity.plot())
		if (iPlayer != -1 and pPlot2 != -1):
			for i in range(pPlot.getNumUnits(), -1, -1):
				pUnit = pPlot.getUnit(i)
				pUnit.setXY(pPlot2.getX(), pPlot2.getY(), true, true, true)
			CyGame().addPlayerAdvanced(iPlayer, iTeam, iLeader, iCiv)
			pPlayer = gc.getPlayer(iPlayer)
			pCity.changeCulture(iPlayer, 100, True)
			pPlayer.acquireCity(pCity,false,false)
			pPlayer.initUnit(gc.getInfoTypeForString('UNIT_ARCHER'), pPlot.getX(), pPlot.getY(), UnitAITypes.NO_UNITAI, DirectionTypes.DIRECTION_SOUTH)
			pPlayer.initUnit(gc.getInfoTypeForString('UNIT_ARCHER'), pPlot.getX(), pPlot.getY(), UnitAITypes.NO_UNITAI, DirectionTypes.DIRECTION_SOUTH)
			pPlayer.initUnit(gc.getInfoTypeForString('UNIT_ARCHER'), pPlot.getX(), pPlot.getY(), UnitAITypes.NO_UNITAI, DirectionTypes.DIRECTION_SOUTH)
			pPlayer.initUnit(gc.getInfoTypeForString('UNIT_ARCHER'), pPlot.getX(), pPlot.getY(), UnitAITypes.NO_UNITAI, DirectionTypes.DIRECTION_SOUTH)
			pPlayer.initUnit(gc.getInfoTypeForString('UNIT_WORKER'), pPlot.getX(), pPlot.getY(), UnitAITypes.NO_UNITAI, DirectionTypes.DIRECTION_SOUTH)
			if iAlignment != -1:
				pPlayer.setAlignment(iAlignment)

	def doCityFire(self, pCity):
		iCount = 0
		for iBuilding in range(gc.getNumBuildingInfos()):
			if pCity.getNumRealBuilding(iBuilding) > 0:
				if gc.getBuildingInfo(iBuilding).getConquestProbability() != 100:
					if CyGame().getSorenRandNum(100, "City Fire") <= 10:
						pCity.setNumRealBuilding(iBuilding, 0)
						CyInterface().addMessage(pCity.getOwner(),True,25,CyTranslator().getText("TXT_KEY_MESSAGE_CITY_FIRE",(gc.getBuildingInfo(iBuilding).getDescription(), )),'',1,gc.getBuildingInfo(iBuilding).getButton(),ColorTypes(8),pCity.getX(),pCity.getY(),True,True)
						iCount += 1
		if iCount == 0:
			CyInterface().addMessage(pCity.getOwner(),True,25,CyTranslator().getText("TXT_KEY_MESSAGE_CITY_FIRE_NO_DAMAGE",()),'AS2D_SPELL_FIRE_ELEMENTAL',1,'Art/Interface/Buttons/Fire.dds',ColorTypes(8),pCity.getX(),pCity.getY(),True,True)

	def doHellTerrain(self):
		iAshenVeil = gc.getInfoTypeForString('RELIGION_THE_ASHEN_VEIL')
		iBurningSands = gc.getInfoTypeForString('TERRAIN_BURNING_SANDS')
		iBanana = gc.getInfoTypeForString('BONUS_BANANA')
		iCotton = gc.getInfoTypeForString('BONUS_COTTON')
		iCorn = gc.getInfoTypeForString('BONUS_CORN')
		iCow = gc.getInfoTypeForString('BONUS_COW')
		iEvil = gc.getInfoTypeForString('ALIGNMENT_EVIL')
		iFarm = gc.getInfoTypeForString('IMPROVEMENT_FARM')
		iFlames = gc.getInfoTypeForString('FEATURE_FLAMES')
		iFlamesSpreadChance = gc.getDefineINT('FLAMES_SPREAD_CHANCE')
		iGulagarm = gc.getInfoTypeForString('BONUS_GULAGARM')
		iHorse = gc.getInfoTypeForString('BONUS_HORSE')
		iInfernal = gc.getInfoTypeForString('CIVILIZATION_INFERNAL')
		iMarble = gc.getInfoTypeForString('BONUS_MARBLE')
		iNeutral = gc.getInfoTypeForString('ALIGNMENT_NEUTRAL')
		iNightmare = gc.getInfoTypeForString('BONUS_NIGHTMARE')
		iPig = gc.getInfoTypeForString('BONUS_PIG')
		iRazorweed = gc.getInfoTypeForString('BONUS_RAZORWEED')
		iRice = gc.getInfoTypeForString('BONUS_RICE')
		iSheep = gc.getInfoTypeForString('BONUS_SHEEP')
		iSheutStone = gc.getInfoTypeForString('BONUS_SHEUT_STONE')
		iSilk = gc.getInfoTypeForString('BONUS_SILK')
		iSnakePillar = gc.getInfoTypeForString('IMPROVEMENT_SNAKE_PILLAR')
		iSugar = gc.getInfoTypeForString('BONUS_SUGAR')
		iToad = gc.getInfoTypeForString('BONUS_TOAD')
		iWheat = gc.getInfoTypeForString('BONUS_WHEAT')
		iCount = CyGame().getGlobalCounter()
		for i in range (CyMap().numPlots()):
			pPlot = CyMap().plotByIndex(i)
			iFeature = pPlot.getFeatureType()
			iTerrain = pPlot.getTerrainType()
			iBonus = pPlot.getBonusType(-1)
			iImprovement = pPlot.getImprovementType()
			bUntouched = true
			if pPlot.isOwned():
				pPlayer = gc.getPlayer(pPlot.getOwner())
				iAlignment = pPlayer.getAlignment()
				if pPlayer.getCivilizationType() == iInfernal:
					pPlot.changePlotCounter(100)
					bUntouched = false
				if (bUntouched and pPlayer.getStateReligion() == iAshenVeil or (iCount >= 50 and iAlignment == iEvil) or (iCount >= 75 and iAlignment == iNeutral)):
					iX = pPlot.getX()
					iY = pPlot.getY()
					for iiX in range(iX-1, iX+2, 1):
						for iiY in range(iY-1, iY+2, 1):
							pAdjacentPlot = CyMap().plot(iiX,iiY)
							if pAdjacentPlot.isNone() == False:
								if pAdjacentPlot.getPlotCounter() > 10:
									pPlot.changePlotCounter(1)
									bUntouched = false
			if (bUntouched and pPlot.isOwned() == false and iCount > 25):
				iX = pPlot.getX()
				iY = pPlot.getY()
				for iiX in range(iX-1, iX+2, 1):
					for iiY in range(iY-1, iY+2, 1):
						pAdjacentPlot = CyMap().plot(iiX,iiY)
						if pAdjacentPlot.isNone() == False:
							if pAdjacentPlot.getPlotCounter() > 10:
								pPlot.changePlotCounter(1)
								bUntouched = false
			iPlotCount = pPlot.getPlotCounter()
			if (bUntouched and iPlotCount > 0):
				pPlot.changePlotCounter(-1)
			if iPlotCount > 9:
				if (iBonus == iSheep or iBonus == iPig):
					pPlot.setBonusType(iToad)
				if (iBonus == iHorse or iBonus == iCow):
					pPlot.setBonusType(iNightmare)
				if (iBonus == iCotton or iBonus == iSilk):
					pPlot.setBonusType(iRazorweed)
				if (iBonus == iBanana or iBonus == iSugar):
					pPlot.setBonusType(iGulagarm)
				if (iBonus == iMarble):
					pPlot.setBonusType(iSheutStone)
				if (iBonus == iCorn or iBonus == iRice or iBonus == iWheat):
					pPlot.setBonusType(-1)
					pPlot.setImprovementType(iSnakePillar)
			if iPlotCount < 10:
				if iBonus == iToad:
					if CyGame().getSorenRandNum(100, "Hell Convert") < 50:
						pPlot.setBonusType(iSheep)
					else:
						pPlot.setBonusType(iPig)
				if iBonus == iNightmare:
					if CyGame().getSorenRandNum(100, "Hell Convert") < 50:
						pPlot.setBonusType(iHorse)
					else:
						pPlot.setBonusType(iCow)
				if iBonus == iRazorweed:
					if CyGame().getSorenRandNum(100, "Hell Convert") < 50:
						pPlot.setBonusType(iCotton)
					else:
						pPlot.setBonusType(iSilk)
				if iBonus == iGulagarm:
					if CyGame().getSorenRandNum(100, "Hell Convert") < 50:
						pPlot.setBonusType(iBanana)
					else:
						pPlot.setBonusType(iSugar)
				if (iBonus == iSheutStone):
					pPlot.setBonusType(iMarble)
				if iImprovement == iSnakePillar:
					pPlot.setImprovementType(iFarm)
					iCount = CyGame().getSorenRandNum(100, "Hell Convert")
					if  iCount < 33:
						pPlot.setBonusType(iCorn)
					else:
						if iCount < 66:
							pPlot.setBonusType(iRice)
						else:
							pPlot.setBonusType(iWheat)
			if iTerrain == iBurningSands:
				if pPlot.isCity() == False:
					if CyGame().getSorenRandNum(100, "Flames") <= iFlamesSpreadChance:
						pPlot.setFeatureType(iFlames, 0)

	def doTurnKhazad(self, iPlayer):
		pPlayer = gc.getPlayer(iPlayer)
		if pPlayer.getNumCities() > 0:
			iVault1 = gc.getInfoTypeForString('BUILDING_DWARVEN_VAULT_EMPTY')
			iVault2 = gc.getInfoTypeForString('BUILDING_DWARVEN_VAULT_LOW')
			iVault3 = gc.getInfoTypeForString('BUILDING_DWARVEN_VAULT')
			iVault4 = gc.getInfoTypeForString('BUILDING_DWARVEN_VAULT_STOCKED')
			iVault5 = gc.getInfoTypeForString('BUILDING_DWARVEN_VAULT_ABUNDANT')
			iVault6 = gc.getInfoTypeForString('BUILDING_DWARVEN_VAULT_FULL')
			iVault7 = gc.getInfoTypeForString('BUILDING_DWARVEN_VAULT_OVERFLOWING')
			iGold = pPlayer.getGold() / pPlayer.getNumCities()
			if iGold <= 49:
				iNewVault = iVault1
			if (iGold >= 50 and iGold <= 99):
				iNewVault = iVault2
			if (iGold >= 100 and iGold <= 149):
				iNewVault = iVault3
			if (iGold >= 150 and iGold <= 199):
				iNewVault = iVault4
			if (iGold >= 200 and iGold <= 299):
				iNewVault = iVault5
			if (iGold >= 300 and iGold <= 499):
				iNewVault = iVault6
			if iGold >= 500:
				iNewVault = iVault7
			for i in range(pPlayer.getNumCities()):
				pCity = pPlayer.getCity(i)
				pCity.setNumRealBuilding(iVault1, 0)
				pCity.setNumRealBuilding(iVault2, 0)
				pCity.setNumRealBuilding(iVault3, 0)
				pCity.setNumRealBuilding(iVault4, 0)
				pCity.setNumRealBuilding(iVault5, 0)
				pCity.setNumRealBuilding(iVault6, 0)
				pCity.setNumRealBuilding(iVault7, 0)
				pCity.setNumRealBuilding(iNewVault, 1)

	def doTurnLuchuirp(self, iPlayer):
		pPlayer = gc.getPlayer(iPlayer)
		py = PyPlayer(iPlayer)
		pBarnaxus = -1
		iBarnaxus = gc.getInfoTypeForString('UNITCLASS_BARNAXUS')
		iCombat1 = gc.getInfoTypeForString('PROMOTION_COMBAT1')
		iCombat2 = gc.getInfoTypeForString('PROMOTION_COMBAT2')
		iCombat3 = gc.getInfoTypeForString('PROMOTION_COMBAT3')
		iCombat4 = gc.getInfoTypeForString('PROMOTION_COMBAT4')
		iCombat5 = gc.getInfoTypeForString('PROMOTION_COMBAT5')
		iEmpower1 = gc.getInfoTypeForString('PROMOTION_EMPOWER1')
		iEmpower2 = gc.getInfoTypeForString('PROMOTION_EMPOWER2')
		iEmpower3 = gc.getInfoTypeForString('PROMOTION_EMPOWER3')
		iEmpower4 = gc.getInfoTypeForString('PROMOTION_EMPOWER4')
		iEmpower5 = gc.getInfoTypeForString('PROMOTION_EMPOWER5')
		iGolem = gc.getInfoTypeForString('PROMOTION_GOLEM')
		if pPlayer.getUnitClassCount(iBarnaxus) > 0:
			for pUnit in py.getUnitList():
				if pUnit.getUnitClassType() == iBarnaxus:
					pBarnaxus = pUnit
		for pUnit in py.getUnitList():
			if pUnit.isHasPromotion(iGolem):
				pUnit.setHasPromotion(iEmpower1, False)
				pUnit.setHasPromotion(iEmpower2, False)
				pUnit.setHasPromotion(iEmpower3, False)
				pUnit.setHasPromotion(iEmpower4, False)
				pUnit.setHasPromotion(iEmpower5, False)
				if (pBarnaxus != -1 and pUnit.getUnitClassType() != iBarnaxus):
					if pBarnaxus.isHasPromotion(iCombat1):
						pUnit.setHasPromotion(iEmpower1, True)
					if pBarnaxus.isHasPromotion(iCombat2):
						pUnit.setHasPromotion(iEmpower2, True)
					if pBarnaxus.isHasPromotion(iCombat3):
						pUnit.setHasPromotion(iEmpower3, True)
					if pBarnaxus.isHasPromotion(iCombat4):
						pUnit.setHasPromotion(iEmpower4, True)
					if pBarnaxus.isHasPromotion(iCombat5):
						pUnit.setHasPromotion(iEmpower5, True)

	def doTurnRatcatchersGuild(self):
		iRatGuild = gc.getInfoTypeForString('CORPORATION_RATCATCHERS_GUILD')
		if CyGame().isCorporationFounded(iRatGuild):
			iValue = -1
			pBestCity = gc.getGame().getHeadquarters(iRatGuild)
			iBestValue = pBestCity.getCrime() + (pBestCity.getPopulation() * 3) + 10
			for iPlayer in range(gc.getMAX_PLAYERS()):
				pPlayer = gc.getPlayer(iPlayer)
				if pPlayer.isAlive():
					for iCity in range(pPlayer.getNumCities()):
						pCity = pPlayer.getCity(iCity)
						iValue = pCity.getCrime() + (pCity.getPopulation() * 3)
						if iValue > iBestValue:
							iBestValue = iValue
							pBestCity = pCity
			if pBestCity.isHeadquartersByType(iRatGuild) == False:
				pOldCity = gc.getGame().getHeadquarters(iRatGuild)
				CyInterface().addMessage(pOldCity.getOwner(),True,25,CyTranslator().getText("TXT_KEY_MESSAGE_RATCATCHERS_GUILD_HQ_MOVE_OUT",()),'AS2D_RATCATCHERS_GUILD',1,'Art/Interface/Buttons/Corporations/Ratcatchers Guild.dds',gc.getInfoTypeForString("COLOR_RED"),pOldCity.getX(),pOldCity.getY(),True,True)
				pBestCity.setHeadquarters(iRatGuild)

	def findClearPlot(self, pUnit, plot):
		BestPlot = -1
		iBestPlot = 0
		if pUnit == -1:
			iX = plot.getX()
			iY = plot.getY()
			for iiX in range(iX-1, iX+2, 1):
				for iiY in range(iY-1, iY+2, 1):
					iCurrentPlot = 0
					pPlot = CyMap().plot(iiX,iiY)
					if pPlot.isNone() == False:
						if pPlot.getNumUnits() == 0:
							if (pPlot.isWater() == plot.isWater() and pPlot.isPeak() == False and pPlot.isCity() == False):
								iCurrentPlot = iCurrentPlot + 5
						if iCurrentPlot >= 1:
							iCurrentPlot = iCurrentPlot + CyGame().getSorenRandNum(5, "FindClearPlot")
							if iCurrentPlot >= iBestPlot:
								BestPlot = pPlot
								iBestPlot = iCurrentPlot
			return BestPlot
		iX = pUnit.getX()
		iY = pUnit.getY()
		for iiX in range(iX-1, iX+2, 1):
			for iiY in range(iY-1, iY+2, 1):
				iCurrentPlot = 0
				pPlot = CyMap().plot(iiX,iiY)
				if pPlot.isNone() == False:
					if pPlot.getNumUnits() == 0:
						if pUnit.canMoveOrAttackInto(pPlot, False):
							iCurrentPlot = iCurrentPlot + 5
					for i in range(pPlot.getNumUnits()):
						if pPlot.getUnit(i).getOwner() == pUnit.getOwner():
							if pUnit.canMoveOrAttackInto(pPlot, False):
								iCurrentPlot = iCurrentPlot + 15
					if pPlot.isCity():
						if pPlot.getPlotCity().getOwner() == pUnit.getOwner():
							iCurrentPlot = iCurrentPlot + 50
					if (iX == iiX and iY == iiY):
						iCurrentPlot = 0
					if iCurrentPlot >= 1:
						iCurrentPlot = iCurrentPlot + CyGame().getSorenRandNum(5, "FindClearPlot")
						if iCurrentPlot >= iBestPlot:
							BestPlot = pPlot
							iBestPlot = iCurrentPlot
		return BestPlot

	def genesis(self, iPlayer):
		iSnow = gc.getInfoTypeForString('TERRAIN_SNOW')
		iTundra = gc.getInfoTypeForString('TERRAIN_TUNDRA')
		iPlains = gc.getInfoTypeForString('TERRAIN_PLAINS')
		iDesert = gc.getInfoTypeForString('TERRAIN_DESERT')
		iGrass = gc.getInfoTypeForString('TERRAIN_GRASS')
		iOasis = gc.getInfoTypeForString('FEATURE_OASIS')
		iForestAncient = gc.getInfoTypeForString('FEATURE_FOREST_ANCIENT')
		iForest = gc.getInfoTypeForString('FEATURE_FOREST')
		for i in range (CyMap().numPlots()):
			pPlot = CyMap().plotByIndex(i)
			if pPlot.getOwner() == iPlayer:
				if(pPlot.getTerrainType() == iSnow):
					pPlot.setTerrainType(iTundra,True,True)
				elif(pPlot.getTerrainType() == iTundra):
					pPlot.setTerrainType(iPlains,True,True)
				elif(pPlot.getTerrainType() == iDesert and pPlot.getFeatureType() != iOasis):
					pPlot.setTerrainType(iPlains,True,True)
				elif(pPlot.getTerrainType() == iPlains):
					pPlot.setTerrainType(iGrass,True,True)
				elif(pPlot.getTerrainType() == iGrass and pPlot.getImprovementType() == -1 and pPlot.getFeatureType() != iForestAncient and pPlot.isPeak() == False):
					pPlot.setFeatureType(iForest, 0)

	def getAshenVeilCity(self, iNum):
		iInfernal = gc.getInfoTypeForString('CIVILIZATION_INFERNAL')
		iVeil = gc.getInfoTypeForString('RELIGION_THE_ASHEN_VEIL')
		iBestValue1 = 0
		iBestValue2 = 0
		iBestValue3 = 0
		pBestCity1 = -1
		pBestCity2 = -1
		pBestCity3 = -1
		for iPlayer in range(gc.getMAX_PLAYERS()):
			pPlayer = gc.getPlayer(iPlayer)
			if (pPlayer.isAlive() and pPlayer.getCivilizationType() != iInfernal):
				for iCity in range(pPlayer.getNumCities()):
					pCity = pPlayer.getCity(iCity)
					if (pCity.isHasReligion(iVeil) and pCity.isCapital() == False):
						bValid = True
						iValue = pCity.getPopulation() * 100
						iValue += pCity.getCulture(iPlayer) / 3
						iValue += pCity.getNumBuildings() * 10
						iValue += pCity.getNumWorldWonders() * 100
						iValue += pCity.countNumImprovedPlots()
						if iValue > iBestValue1:
							iBestValue3 = iBestValue2
							pBestCity3 = pBestCity2
							iBestValue2 = iBestValue1
							pBestCity2 = pBestCity1
							iBestValue1 = iValue
							pBestCity1 = pCity
							bValid = False
						if (bValid and iValue > iBestValue2):
							iBestValue3 = iBestValue2
							pBestCity3 = pBestCity2
							iBestValue2 = iValue
							pBestCity2 = pCity
							bValid = False
						if (bValid and iValue > iBestValue3):
							iBestValue3 = iValue
							pBestCity3 = pCity
		if iNum == 1:
			return pBestCity1
		if iNum == 2:
			return pBestCity2
		if iNum == 3:
			return pBestCity3
		return -1

	def getCivilization(self, iCiv):
		i = -1
		for iPlayer in range(gc.getMAX_PLAYERS()):
			pPlayer = gc.getPlayer(iPlayer)
			if pPlayer.getCivilizationType() == iCiv:
				i = iPlayer
		return i

	def getHero(self, pPlayer):
		iHero = -1
		if pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_BANNOR'):
			iHero = gc.getInfoTypeForString('UNITCLASS_DONAL')
		if pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_MALAKIM'):
			iHero = gc.getInfoTypeForString('UNITCLASS_TEUTORIX')
		if pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_ELOHIM'):
			iHero = gc.getInfoTypeForString('UNITCLASS_CORLINDALE')
		if pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_MERCURIANS'):
			iHero = gc.getInfoTypeForString('UNITCLASS_BASIUM')
		if pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_LANUN'):
			iHero = gc.getInfoTypeForString('UNITCLASS_GUYBRUSH')
		if pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_KURIOTATES'):
			iHero = gc.getInfoTypeForString('UNITCLASS_EURABATRES')
		if pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_LJOSALFAR'):
			iHero = gc.getInfoTypeForString('UNITCLASS_GILDEN')
		if pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_KHAZAD'):
			iHero = gc.getInfoTypeForString('UNITCLASS_MAROS')
		if pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_HIPPUS'):
			iHero = gc.getInfoTypeForString('UNITCLASS_MAGNADINE')
		if pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_AMURITES'):
			iHero = gc.getInfoTypeForString('UNITCLASS_GOVANNON')
		if pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_BALSERAPHS'):
			iHero = gc.getInfoTypeForString('UNITCLASS_LOKI')
		if pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_CLAN_OF_EMBERS'):
			iHero = gc.getInfoTypeForString('UNITCLASS_RANTINE')
		if pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_SVARTALFAR'):
			iHero = gc.getInfoTypeForString('UNITCLASS_ALAZKAN')
		if pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_CALABIM'):
			iHero = gc.getInfoTypeForString('UNITCLASS_LOSHA')
		if pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_SHEAIM'):
			iHero = gc.getInfoTypeForString('UNITCLASS_ABASHI')
		if pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_SIDAR'):
			iHero = gc.getInfoTypeForString('UNITCLASS_RATHUS')
		if pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_ILLIANS'):
			iHero = gc.getInfoTypeForString('UNITCLASS_WILBOMAN')
		if pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_INFERNAL'):
			iHero = gc.getInfoTypeForString('UNITCLASS_HYBOREM')
		return iHero

	def getLeader(self, iLeader):
		i = -1
		for iPlayer in range(gc.getMAX_PLAYERS()):
			pPlayer = gc.getPlayer(iPlayer)
			if pPlayer.getLeaderType() == iLeader:
				i = iPlayer
		return i

	def getOpenPlayer(self):
		i = -1
		for iPlayer in range(gc.getMAX_PLAYERS()):
			pPlayer = gc.getPlayer(iPlayer)
			if (pPlayer.isEverAlive() == False and i == -1):
				i = iPlayer
		return i

	def getMaxSprawlingCities(self):
		i = gc.getDefineINT('SPRAWLING_NUMBER_OF_CITIES')
		if CyMap().getWorldSize() == gc.getInfoTypeForString('WORLDSIZE_DUEL'):
			i = i - 1
		if CyMap().getWorldSize() == gc.getInfoTypeForString('WORLDSIZE_LARGE'):
			i = i + 1
		if CyMap().getWorldSize() == gc.getInfoTypeForString('WORLDSIZE_HUGE'):
			i = i + 2
		return i

	def getUnitStrString(self, pUnit, bDetail):
		if (gc.getUnitInfo(pUnit.getUnitType()).getAirCombat() > 0):
			iStrength = pUnitTypeInfo.getAirCombat()
			szText = u"%i "%iStrength + u"%c" % CyGame().getSymbolID( FontSymbols.STRENGTH_CHAR )
			return szText
		iAttack = pUnit.baseCombatStr(true)
		iDefense = pUnit.baseCombatStr(false)
		if (pUnit.isFighting()):
			szText = u"?/%d" %(iAttack)
		else:
			if bDetail == True:
				iAttack = iAttack - pUnit.getCombatCold() - pUnit.getCombatDeath() - pUnit.getCombatFire() - pUnit.getCombatHoly() - pUnit.getCombatLightning() - pUnit.getCombatPoison() - pUnit.getCombatUnholy()
				iDefense = iDefense - pUnit.getCombatCold() - pUnit.getCombatDeath() - pUnit.getCombatFire() - pUnit.getCombatHoly() - pUnit.getCombatLightning() - pUnit.getCombatPoison() - pUnit.getCombatUnholy()
			if (pUnit.isHurt()):
				if iAttack == iDefense:
					szText = u"%.1f/%d" %(((float(iAttack * pUnit.currHitPoints())) / (float(pUnit.maxHitPoints()))), iAttack)
				else:
					szText = u"%.1f/%.1f" %(((float(iAttack * pUnit.currHitPoints())) / (float(pUnit.maxHitPoints()))), ((float(iDefense * pUnit.currHitPoints())) / (float(pUnit.maxHitPoints()))))
			else:
				if iAttack == iDefense:
					szText = u"%d" %(iAttack)
				else:
					szText = u"%d/%d" %(iAttack, iDefense)
			if bDetail == True:
				if pUnit.getCombatCold() != 0:
					szText += u" (+%i %s)" %(pUnit.getCombatCold(),CyTranslator().getText("TXT_KEY_DAMAGE_COLD_TAG",()))
				if pUnit.getCombatDeath() != 0:
					szText += u" (+%i %s)" %(pUnit.getCombatDeath(),CyTranslator().getText("TXT_KEY_DAMAGE_DEATH_TAG",()))
				if pUnit.getCombatFire() != 0:
					szText += u" (+%i %s)" %(pUnit.getCombatFire(),CyTranslator().getText("TXT_KEY_DAMAGE_FIRE_TAG",()))
				if pUnit.getCombatHoly() != 0:
					szText += u" (+%i %s)" %(pUnit.getCombatHoly(),CyTranslator().getText("TXT_KEY_DAMAGE_HOLY_TAG",()))
				if pUnit.getCombatLightning() != 0:
					szText += u" (+%i %s)" %(pUnit.getCombatLightning(),CyTranslator().getText("TXT_KEY_DAMAGE_LIGHTNING_TAG",()))
				if pUnit.getCombatPoison() != 0:
					szText += u" (+%i %s)" %(pUnit.getCombatPoison(),CyTranslator().getText("TXT_KEY_DAMAGE_POISON_TAG",()))
				if pUnit.getCombatUnholy() != 0:
					szText += u" (+%i %s)" %(pUnit.getCombatUnholy(),CyTranslator().getText("TXT_KEY_DAMAGE_UNHOLY_TAG",()))
		szText += u"%c" %(CyGame().getSymbolID(FontSymbols.STRENGTH_CHAR))
		return szText

	def giftUnit(self, iUnit, iCivilization, iXP, pFromPlot, iFromPlayer):
		iAngel = gc.getInfoTypeForString('UNIT_ANGEL')
		iManes = gc.getInfoTypeForString('UNIT_MANES')
		if (iUnit == iAngel or iUnit == iManes):
			iChance = 100 - (CyGame().countCivPlayersAlive() * 3)
			iChance = iChance + iXP
			if iChance < 5:
				iChance = 5
			if iChance > 95:
				iChance = 95
			if CyGame().getSorenRandNum(100, "Gift Unit") > iChance:
				iUnit = -1
		if iUnit != -1:
			for iPlayer in range(gc.getMAX_PLAYERS()):
				pPlayer = gc.getPlayer(iPlayer)
				if (pPlayer.isAlive()):
					if pPlayer.getCivilizationType() == iCivilization:
						py = PyPlayer(iPlayer)
						if pPlayer.getNumCities() > 0:
							iRnd = CyGame().getSorenRandNum(py.getNumCities(), "Gift Unit")
							pCity = py.getCityList()[iRnd]
							pPlot = pCity.plot()
							newUnit = pPlayer.initUnit(iUnit, pPlot.getX(), pPlot.getY(), UnitAITypes.NO_UNITAI, DirectionTypes.DIRECTION_NORTH)
							newUnit.changeExperience(iXP, -1, false, false, false)
							if (pFromPlot != -1 and gc.getPlayer(iFromPlayer).isHuman()):
								if iUnit == iManes:
									CyInterface().addMessage(iFromPlayer,True,25,CyTranslator().getText("TXT_KEY_MESSAGE_UNIT_FALLS",()),'AS2D_UNIT_FALLS',1,'Art/Interface/Buttons/Promotions/Demon.dds',ColorTypes(7),pFromPlot.getX(),pFromPlot.getY(),True,True)
								if iUnit == iAngel:
									CyInterface().addMessage(iFromPlayer,True,25,CyTranslator().getText("TXT_KEY_MESSAGE_UNIT_RISES",()),'AS2D_UNIT_FALLS',1,'Art/Interface/Buttons/Promotions/Angel.dds',ColorTypes(7),pFromPlot.getX(),pFromPlot.getY(),True,True)
							if pPlayer.isHuman():
								if iUnit == iManes:
									CyInterface().addMessage(iPlayer,True,25,CyTranslator().getText("TXT_KEY_MESSAGE_ADD_MANES",()),'AS2D_UNIT_FALLS',1,'Art/Interface/Buttons/Promotions/Demon.dds',ColorTypes(7),pPlot.getX(),pPlot.getY(),True,True)
								if iUnit == iAngel:
									CyInterface().addMessage(iPlayer,True,25,CyTranslator().getText("TXT_KEY_MESSAGE_ADD_ANGEL",()),'AS2D_UNIT_FALLS',1,'Art/Interface/Buttons/Promotions/Angel.dds',ColorTypes(7),pPlot.getX(),pPlot.getY(),True,True)
							if (pPlayer.isHuman() == False and iUnit == iManes and pCity != -1):
								if CyGame().getSorenRandNum(100, "Manes") < (100 - (pCity.getPopulation() * 5)):
									pCity.changePopulation(1)
									newUnit.kill(True,0)

	def showUniqueImprovements(self, iPlayer):
		pPlayer = gc.getPlayer(iPlayer)
		iTeam = pPlayer.getTeam()
		for i in range (CyMap().numPlots()):
			pPlot = CyMap().plotByIndex(i)
			if pPlot.getImprovementType() != -1:
				if gc.getImprovementInfo(pPlot.getImprovementType()).isUnique():
					pPlot.setRevealed(iTeam, True, False, TeamTypes.NO_TEAM)

	def startWar(self, iPlayer, i2Player):
		iTeam = gc.getPlayer(iPlayer).getTeam()
		i2Team = gc.getPlayer(i2Player).getTeam()
		eTeam = gc.getTeam(iTeam)
		e2Team = gc.getTeam(i2Team)
		if eTeam.isAlive():
			if e2Team.isAlive():
				if eTeam.isAtWar(i2Team) == False:
					if iTeam != i2Team:
						if eTeam.isHasMet(i2Team):
							eTeam.declareWar(i2Team, false, WarPlanTypes.WARPLAN_LIMITED)

	def warScript(self, iPlayer):
		pPlayer = gc.getPlayer(iPlayer)
		iEnemy = -1
		for iPlayer2 in range(gc.getMAX_PLAYERS()):
			pPlayer2 = gc.getPlayer(iPlayer2)
			if pPlayer2.isAlive():
				iTeam = gc.getPlayer(iPlayer).getTeam()
				iTeam2 = gc.getPlayer(iPlayer2).getTeam()
				eTeam = gc.getTeam(iTeam)
				if eTeam.isAVassal() == False:
					if eTeam.isAtWar(iTeam2):
						if CyGame().getSorenRandNum(100, "War Script") < 5:
							self.dogpile(iPlayer, iPlayer2)
					if self.warScriptAllow(iPlayer, iPlayer2):
						if pPlayer2.getBuildingClassMaking(gc.getInfoTypeForString('BUILDINGCLASS_TOWER_OF_MASTERY')) > 0:
							if eTeam.getAtWarCount(True) == 0:
								self.startWar(iPlayer, iPlayer2)
						if (pPlayer2.getNumBuilding(gc.getInfoTypeForString('BUILDING_ALTAR_OF_THE_LUONNOTAR_DIVINE')) > 0 or pPlayer2.getNumBuilding(gc.getInfoTypeForString('BUILDING_ALTAR_OF_THE_LUONNOTAR_EXALTED')) > 0):
							if pPlayer.getAlignment() == gc.getInfoTypeForString('ALIGNMENT_EVIL'):
								if eTeam.getAtWarCount(True) == 0:
									self.startWar(iPlayer, iPlayer2)
						if pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_MERCURIANS'):
							if pPlayer2.getStateReligion() == gc.getInfoTypeForString('RELIGION_THE_ASHEN_VEIL'):
								self.startWar(iPlayer, iPlayer2)
						if CyGame().getGlobalCounter() > 20:
							if pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_SVARTALFAR'):
								if (pPlayer2.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_LJOSALFAR') and CyGame().getPlayerRank(iPlayer) > CyGame().getPlayerRank(iPlayer2)):
									self.startWar(iPlayer, iPlayer2)
							if pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_LJOSALFAR'):
								if (pPlayer2.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_SVARTALFAR') and CyGame().getPlayerRank(iPlayer) > CyGame().getPlayerRank(iPlayer2)):
									self.startWar(iPlayer, iPlayer2)
						if (CyGame().getGlobalCounter() > 40 or pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_INFERNAL') or pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_DOVIELLO')):
							if pPlayer.getAlignment() == gc.getInfoTypeForString('ALIGNMENT_EVIL'):
								if (eTeam.getAtWarCount(True) == 0 and CyGame().getPlayerRank(iPlayer2) > CyGame().getPlayerRank(iPlayer)):
									if (iEnemy == -1 or CyGame().getPlayerRank(iPlayer2) > CyGame().getPlayerRank(iEnemy)):
										iEnemy = iPlayer2
		if iEnemy != -1:
			if CyGame().getPlayerRank(iPlayer) > CyGame().getPlayerRank(iEnemy):
				self.startWar(iPlayer, iEnemy)

	def warScriptAllow(self, iPlayer, iPlayer2):
		pPlayer = gc.getPlayer(iPlayer)
		pPlayer2 = gc.getPlayer(iPlayer2)
		iTeam = gc.getPlayer(iPlayer).getTeam()
		iTeam2 = gc.getPlayer(iPlayer2).getTeam()
		eTeam = gc.getTeam(iTeam)
		if iPlayer == gc.getBARBARIAN_PLAYER():
			return False
		if eTeam.isHasMet(iTeam2) == False:
			return False
		if eTeam.AI_getAtPeaceCounter(iTeam2) < 20:
			return False
#		if pPlayer.AI_getAttitude(iPlayer2) <= gc.getLeaderHeadInfo(pPlayer.getLeaderType()).getDeclareWarRefuseAttitudeThreshold():
#			return False
		if eTeam.isAtWar(iTeam2):
			return False
		if pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_INFERNAL'):
			if pPlayer2.getStateReligion() == gc.getInfoTypeForString('RELIGION_THE_ASHEN_VEIL'):
				return False
		return True

	def dogpile(self, iPlayer, iVictim):
		pPlayer = gc.getPlayer(iPlayer)
		for iPlayer2 in range(gc.getMAX_PLAYERS()):
			pPlayer2 = gc.getPlayer(iPlayer2)
			iChance = -1
			if pPlayer2.isAlive():
				if (self.dogPileAllow(iPlayer, iPlayer2) and self.warScriptAllow(iPlayer2, iVictim)):
					iChance = pPlayer2.AI_getAttitude(iPlayer) * 5
					if iChance > 0:
						iChance = iChance - (pPlayer2.AI_getAttitude(iVictim) * 5) - 10
						if CyGame().isOption(gc.getInfoTypeForString('GAMEOPTION_AGGRESSIVE_AI')) == False:
							iChance = iChance - 10
						if iChance > 0:
							iChance = iChance + (CyGame().getGlobalCounter() / 3)
							if pPlayer2.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_BALSERAPHS'):
								iChance = CyGame().getSorenRandNum(50, "Dogpile")
							if CyGame().getSorenRandNum(100, "Dogpile") < iChance:
								self.startWar(iPlayer2, iVictim)

	def dogPileAllow(self, iPlayer, iPlayer2):
		pPlayer = gc.getPlayer(iPlayer)
		pPlayer2 = gc.getPlayer(iPlayer2)
		iTeam = gc.getPlayer(iPlayer).getTeam()
		iTeam2 = gc.getPlayer(iPlayer2).getTeam()
		if iPlayer == iPlayer2:
			return False
		if iTeam == iTeam2:
			return False
		if pPlayer2.isHuman():
			return False
		if pPlayer2.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_ELOHIM'):
			return False
		if gc.getTeam(iTeam2).isAVassal():
			return False
		return True

	def warn(self, iPlayer, szText, pPlot):
		pPlayer = gc.getPlayer(iPlayer)
		for iPlayer2 in range(gc.getMAX_PLAYERS()):
			pPlayer2 = gc.getPlayer(iPlayer2)
			if (pPlayer2.isAlive() and iPlayer != iPlayer2):
				if pPlayer2.isHuman():
					popupInfo = CyPopupInfo()
					popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
					popupInfo.setText(szText)
					popupInfo.setOnClickedPythonCallback("selectWarn")
					popupInfo.addPythonButton(CyTranslator().getText("TXT_KEY_MAIN_MENU_OK",()), "")
					popupInfo.addPopup(iPlayer2)
				if pPlot != -1:
					CyInterface().addMessage(iPlayer2,True,25,CyTranslator().getText("TXT_KEY_MESSAGE_ALTAR_OF_THE_LUONNOTAR",()),'AS2D_DISCOVERBONUS',1,'Art/Interface/Buttons/Buildings/AltaroftheLuonnotar.dds',ColorTypes(7),pPlot.getX(),pPlot.getY(),True,True)
